package day03;

import day04.Car;

public class Memory {
    public static void main(String[] args) {
        /*栈测试*/
        /*double card = 10;//饭卡里有10块钱
        char ip = buy('鱼', card);
        System.out.println("card中的余额：" + card);
         */
        //创建了一个饭卡对象，封装饭卡的余额
        Card lpCard=new Card("LP",10);
        char lp=buy('鱼',lpCard);
        System.out.println("饭卡的余额"+lpCard.bal);

        /*对象生命周期的测试*/
        //小明点了一份小笼包，一笼四个
        char[] my = new char[]{'包', '包', '包', '包'};
        //小红点了一份烧卖，一份五个
        char[] gf = new char[]{'烧', '烧', '烧', '烧', '烧'};
        //小明吃完了所有的小笼包
        for (int i = 0; i < my.length; i++) {
            my[i] = 0;
        }
        System.out.println(my);
        //小红只吃了两个烧卖
        gf[0] = 0;
        gf[1] = 0;
        System.out.println(gf);
        //小明和小红抢一个烧卖
        my = gf;
        //小明吃了第三个
        my[2] = 0;
        //小红吃了第四个
        gf[3] = 0;
        System.out.println(gf);
        //小红吃了最后一个烧卖
        gf[4] = 0;
        //仅将一个变量设置为null是不够的
        gf = null;
        my = null;

        /*堆测试*/
        showMem();
        for (int i = 0; i < 200; i++) {

            char[] chs = new char[10 * 1024 * 1024 / 2];
            chs = null;
            System.gc();
        }
        showMem();
    }

    /**
     * 使用Card类型对象作为参数的buy
     *
     * @param what 菜名
     * @param card Card类型对象
     * @return 菜名
     */
    public static char buy(char what, Card card) {
        card.bal-=3;//从饭卡对象的bal属性中减3元
        System.out.println("余额+"+card.bal);//打印饭卡对象的余额属性
        return what;
    }

    /**
     * 帮同学打饭
     *
     * @param what 菜名
     * @param card 饭卡余额
     * @return 打到的菜名
     */
    public static char buy(char what, double card) {
        card -= 3;//每次减3元
        System.out.println("余额：" + card);
        return what;//返回达到的饭菜
    }

    /**
     * 显示JVM三大指标
     */
    public static void showMem() {
        //首先要获得运行时对象
        Runtime rt = Runtime.getRuntime();
        System.out.println("Max:" + rt.maxMemory() / 1024 / 1024 + "M;"
                + "Total" + (rt.totalMemory() / 1024 / 1024) + "M;"
                + "Free:" + (rt.freeMemory() / 1024 / 1024 + "M;"));
    }
}
